import "mars3d/dist/mars3d.css";
import * as mars3d from "mars3d";
export const eventTarget = new mars3d.BaseClass();

// 框选查询 矩形
export async function drawRectangle({ map, callback }) {

    if (!map) {
        throw new Error("Map is not defined");
    }
    map.graphicLayer.clear();

    const graphic = await map.graphicLayer.startDraw({
        type: "rectangle",
        style: {
            fill: true,
            color: "rgba(255,255,0,0.2)",
            outline: true,
            outlineWidth: 2,
            outlineColor: "rgba(255,255,0,1)"
        }
    });
    console.log("绘制完成，graphic:", graphic);
    // 这些都是错误的排查日志
    if (!graphic) {
      console.error("graphic 为 undefined");
      return;
    }
  
    if (!graphic._rectangle_draw) {
      console.error("graphic._rectangle_draw 为 undefined");
      return;
    }
  
    console.log("graphic._rectangle_draw:", graphic._rectangle_draw);
  
    const rectangle = mars3d.PolyUtil.formatRectangle(graphic._rectangle_draw);
    console.log("格式化后的矩形:", rectangle);
  
    if (!rectangle) {
      console.error("rectangle 为 undefined");
      return;
    }
  
    eventTarget.fire("drawExtent", { extent: JSON.stringify(rectangle) });
    console.log("触发 drawExtent 事件，rectangle:", rectangle);
  
    // 调用回调函数并传递拉框查询的结果
    if (typeof callback === 'function') {
      console.log('执行回调函数');
      callback(rectangle);
    } else {
      console.error('callback 不是函数');
    }
}

// 需要覆盖config.json中地图属性参数（当前示例框架中自动处理合并）
// export const mapOptions = {
//     layers: [
//       {
//         type: "geojson",
//         name: "示例数据",
//         url: "//data.mars3d.cn/file/geojson/mars3d-draw.json",
//         popup: "{type} {name}",
//         show: true
//       },
//       {
//         type: "3dtiles",
//         name: "测试模型",
//         url: "//data.mars3d.cn/3dtiles/bim-daxue/tileset.json",
//         position: { lng: 116.313536, lat: 31.217297, alt: 80 },
//         scale: 100,
//         show: true
//       }
//     ]
//   }

export function createMap(map,mapOptions) {
    if (map) {
      alert("地图已存在,请勿重复创建!")
      return map
    }
    alert("创建地图成功!")
    map = new mars3d.Map("mars3dContainer", mapOptions)
    return map
  }
  export function destroyMap(map) {
    if (!map) {
      alert("地图已销毁,无需重复销毁!");
      return;
    }
    map.destroy();
    map = null;
  }



  export let graphicLayer // 矢量图层对象
  export let colorRamp // 颜色渐变对象

export function hongshui(map) {

  graphicLayer = new mars3d.layer.GraphicLayer()
  map.addLayer(graphicLayer) // 在layer上绑定监听事件

 

  graphicLayer.on(mars3d.EventType.click, function (event) {
    const pickedItem = event.pickedObject?.data
    console.log("单击了合并对象中的单个值为", pickedItem)
  })

  colorRamp = new mars3d.ColorRamp({
    steps: [0, 30],
    colors: ["rgb(33, 113, 181)", "rgb(8, 48, 107)"]
  })

  let progressValue = 0; // 当前进度
  let currentGraphic = null; // 当前显示的graphic

  const intervalId = setInterval(() => {
    progressValue++
    if (progressValue < 315) {
      loadAndRenderGeoJSON(progressValue)
    } else {
      clearInterval(intervalId)
    }
  }, 200)
}

const floods = [] // 缓存的过渡graphic


  // async function loadAndRenderGeoJSON(fileIndex, currentGraphic) {
  async function loadAndRenderGeoJSON(fileIndex) {
    // const url = `//data.mars3d.cn/file/apidemo/floods/${fileIndex}.json`
    // const features = await mars3d.Util.sendAjax({ url })
    // http://localhost:8080/geoserver/cite/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=cite%3Aflood_elements_0&maxFeatures=50&outputFormat=application%2Fjson
    
  //   const filePath = `http://localhost:8080/geoserver/wlwd/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=wlwd%3Aflood_elements_${
  //   fileIndex
  // }&maxFeatures=500000&outputFormat=application%2Fjson`;
     const filePath = `http://10.3.18.162:8080/geoserver/wlwd/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=wlwd%3Aflood_elements_${fileIndex}&maxFeatures=5000&outputFormat=application%2Fjson`;
     //const filePath = `./public/${fileIndex}.json`;

    // const filePath = `//data.mars3d.cn/file/apidemo/floods/${fileIndex}.json`
    // 使用fs模块读取本地文件

    console.log('文件个数',fileIndex,"文件路径:", filePath);
    const response = await fetch(filePath);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    console.log("fetch 请求成功，开始解析 JSON 数据");
    const responseText = await response.text();
    // console.log("响应内容:", responseText);

    // 尝试解析 JSON 数据
    const features = JSON.parse(responseText);

    // 打印 features 数据
    // console.log("获取到的 features 数据:", features.features[0]);
    // console.log("获取到的 features 数据:", features[1].c);
    // features[1].c.map(item => {
    // console.log(item);
    // })

    const instances = []

    features.features.forEach((feature) => {
    // features.forEach((feature) => {
      const coordinates = feature.geometry.coordinates;
      // 高程
      const height = feature.properties.Surface_el;
      // 水深
      const depth = feature.properties.Total_wate;

      coordinates.forEach((coordinate1) => {
        coordinate1.forEach((coordinate2) => {
          coordinate2.pop();
          coordinate2.forEach((coordinate3) => {
            coordinate3.push(height);
            // console.log("coordinate3", coordinate3);
          });
        });
      });

    instances.push({
      positions: coordinates[0],
      style: {
        color: colorRamp.getColor(fileIndex * 10), // 洪水颜色
      },
      attr: { depth: depth },
    });
    });

    // if (currentGraphic) {
    //   graphicLayer.removeGraphic(currentGraphic);
    // }
    // console.log("创建的 instances:", instances);
    
    const graphic = new mars3d.graphic.PolygonCombine({
      instances: instances, // 高亮时的样式
      popup: `深度:{depth}米`
    })
    graphicLayer.addGraphic(graphic)
  
    await graphic.readyPromise

    // currentGraphic = graphic;
  
    // 避免闪烁 + 占用内存 综合考虑，保留过渡的graphic
    if (floods.length > 3) {
      let a = floods.shift();
      if (a) {
        a.remove();
      }
    }
    floods.push(graphic)
  }
  
